package com.roncoo.education.util;


import cn.hutool.core.convert.Convert;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class MyJwtUtil {

    @Value("${jwt.secret}")
    private String secret;



    public String generateToken(Long id,String username) {
        String secretKey = "mySecretKey"; // 密钥
        Map<String,Object> map = new HashMap(){
            private static final long serialVersionUID = 1L;
            {
                put("uname",username);
                put("uid",id);
                // 15天时间后过期
                put("exp",System.currentTimeMillis() + 1000 * 60 * 60 * 24* 15);
            }
        };
        String token = JWTUtil.createToken(map, secret.getBytes());
        return token;
    }

    public Long getUsernameFromToken(String token) {
        JWTPayload payload = JWTUtil.parseToken(token).getPayload();
        Object obj = payload.getClaim("uid");
        if(obj!=null) {
            return Convert.toLong(obj);
        }
        return 1l;
    }

    public boolean validateToken(String token) {
        try {
            return JWTUtil.verify(token,secret.getBytes());
        } catch (Exception e) {
            return false;
        }
    }
}